package cn.exlu.wxcall;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import cn.exlu.wxcall.util.StringUtil;



public class MainActivity extends Activity {
	private static int REQUEST_IMAGE_CAPTURE = 1;
	private String mCurrentPhotoPath;
	
	private Context context; 
	private Button btnTakePic;
	private Button btnSubmit;
	private Button btnCancel;
	private ImageView imgPreview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        
        btnTakePic = (Button) this.findViewById(R.id.btnTakePic);
        btnSubmit = (Button) this.findViewById(R.id.btnSubmit);
        btnCancel = (Button) this.findViewById(R.id.btnCancel);
        imgPreview = (ImageView) this.findViewById(R.id.imgPreview);
        
        btnTakePic.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				dispatchTakePictureIntent();
		        
		       
				
			}
        	
        });
        
        btnCancel.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				finish();
				return;
				
			}
        	
        });
        
        btnSubmit.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// 提交表单
				EditText txtUserPhone = (EditText)findViewById(R.id.txtUserPhone);
				EditText txtUserName = (EditText)findViewById(R.id.txtUserName);
				
				String userPhone = txtUserPhone.getText().toString();
				String userName = txtUserName.getText().toString();
				Context context = getApplicationContext();
				if(StringUtil.isNullOrEmpty(userPhone)){
					Toast toast = Toast.makeText(context, "请输入手机号！", Toast.LENGTH_SHORT);
					toast.show();
					return;
				}
				
				if(StringUtil.isNullOrEmpty(userName)){
					Toast toast = Toast.makeText(context, "请输入姓名！", Toast.LENGTH_SHORT);
					toast.show();
					return;
				}
				
				if(StringUtil.isNullOrEmpty(mCurrentPhotoPath)){
					Toast toast = Toast.makeText(context, "请选择照片！", Toast.LENGTH_SHORT);
					toast.show();
					return;
				}
				
				SharedPreferences sharedPref = context.getSharedPreferences(
				        getString(R.string.data_userinfos), Context.MODE_PRIVATE);
				
				SharedPreferences.Editor editor = sharedPref.edit();
				
				editor.putString(userPhone, userPhone + "###"+userName +"###"+mCurrentPhotoPath);
				
				editor.commit();
				
				Toast toast = Toast.makeText(context, "已保存", Toast.LENGTH_SHORT);
				toast.show();
				
//				Intent intent1 = new Intent(context, WXCallList_Activity.class);
//				startActivity(intent1);
				finish();
				return;
				
			}
        	
        });
        
    }
    
    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
              
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                                                      "cn.exlu.wxcall.android.fileprovider",
                                                      photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
    	// 创建菜单
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_list) {
        	this.finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
		if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
			// Get the dimensions of the View
		    int targetW = imgPreview.getWidth();
		    int targetH = imgPreview.getHeight();

		    // Get the dimensions of the bitmap
		    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
		    bmOptions.inJustDecodeBounds = true;
		    BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
		    int photoW = bmOptions.outWidth;
		    int photoH = bmOptions.outHeight;

		    // Determine how much to scale down the image
		    int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

		    // Decode the image file into a Bitmap sized to fill the View
		    bmOptions.inJustDecodeBounds = false;
		    bmOptions.inSampleSize = scaleFactor;
		    bmOptions.inPurgeable = true;

		    Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
		    imgPreview.setImageBitmap(bitmap);
	        
	        
	    }
	}
	
	private File createImageFile() throws IOException {
	    // Create an image file name
	    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
	    String imageFileName = "JPEG_" + timeStamp + "_";
	    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
	    File image = File.createTempFile(
	        imageFileName,  /* prefix */
	        ".jpg",         /* suffix */
	        storageDir      /* directory */
	    );

	    // Save a file: path for use with ACTION_VIEW intents
	    mCurrentPhotoPath = image.getAbsolutePath();
	    return image;
	}
}
